package com.ouyunc.web.exception.handler;


import com.ouyunc.common.constant.enums.ResponseCodeEnum;
import com.ouyunc.common.base.ResponseResult;
import com.ouyunc.web.exception.CustomerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @Author fangzhenxun
 * @Description 全局异常处理器
 * PropertyResourceBundle
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {
    Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 服务器内部错误，RuntimeException
     **/
    @ExceptionHandler(value = CustomerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult runtimeExceptionHandler(CustomerException ex) {
        log.error(getErrorMsg(ex));
        return ResponseResult.error("自定义异常: " + ex.getMessage());
    }

    /**
     * 服务器内部错误，RuntimeException
     **/
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult runtimeExceptionHandler(RuntimeException ex) {
        log.error(getErrorMsg(ex));
        return ResponseResult.error("服务器内部异常: " + ex.getMessage());
    }
    /**
     * 非法参数，IllegalArgumentException
     **/
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult runtimeExceptionHandler(IllegalArgumentException ex) {
        log.error(getErrorMsg(ex));
        return ResponseResult.error(ResponseCodeEnum.BAD_REQUEST,"非法参数: "+ex.getMessage());
    }

    /**
     * @Author fangzhenxun
     * @Description  获取错误栈，异常信息
     * @param e
     * @return java.lang.String
     **/
    private static String getErrorMsg(Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append(e).append("\r\n");
        for (StackTraceElement stackTraceElement : stackTrace) {
            sb.append("\tat ").append(stackTraceElement.getClassName()).append(".")
                    .append(stackTraceElement.getMethodName())
                    .append("(").append(stackTraceElement.getFileName()).append(":").append(stackTraceElement.getLineNumber())
                    .append(")\r\n");
        }
        return sb.toString();
    }
}
